package com.yangyu.service;

import com.yangyu.currency.Constant;
import com.yangyu.currency.StatusCode;
import com.yangyu.mapper.FileMapper;
import com.yangyu.message.BaseRsp;
import com.yangyu.pojo.File;
import com.yangyu.util.SnowflakeIdUtil;
import com.yangyu.util.UploadUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @author 一碗鱼汤面
 * @version V1.0
 * @Package com.yangyu.service
 * @date 2021/1/17 12:49
 */
@Service
public class UploadService {
    @Value("${yyblog.upload.path}")
    private String defaultPath;

    @Autowired
    private FileMapper fileMapper;

    public BaseRsp uploadImg(MultipartFile image) throws IOException {
        String filename = image.getOriginalFilename();
        String suffix = StringUtils.toRootLowerCase(filename.substring(filename.lastIndexOf(".")));
        if (!(Constant.upload.JPG.equals(suffix) || Constant.upload.PNG.equals(suffix))) {
            return new BaseRsp(StatusCode.UploadErrorCode.IMG_SUFFIX_ERROR, "图片格式错误");
        }
        long imgId = SnowflakeIdUtil.generateId();
        String path = defaultPath + imgId + "/";
        UploadUtil.upload(path, image);
        String fullPath = "http://121.41.230.131:3344/" + imgId + "/" + filename;
        File file = new File(imgId, fullPath);
        fileMapper.addFile(file);
        return new BaseRsp(file);
    }
}
